package com.alibaba.csp.sentinel.demo.zuul.gateway.controller;

import com.alibaba.csp.sentinel.demo.zuul.gateway.sentinel.HeaderMapRequestWrapper;
import com.alibaba.csp.sentinel.demo.zuul.gateway.vo.BaseResultVo;
import com.netflix.zuul.context.RequestContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author gaozq
 */
@RestController
public class SentinelBlockExceptionErrorController implements ErrorController {
    @Value("${error.path:/error}")
    private String errorPath;

    @Override
    public String getErrorPath() {
        return errorPath;
    }


    /**
     * 问题是不光拦截了限流异常， 也拦截了其他异常
     */
    @RequestMapping(value = "${error.path:/error}", produces = "application/vnd.error+json")
    public BaseResultVo error(HttpServletRequest request) {

        /*final int status = getErrorStatus(request);
        final String errorMessage = getErrorMessage(request);
        */

        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode != null) {
            if (429 == statusCode) {
                return BaseResultVo.error("访问频率测试，请勿频繁点击，如有问题联系技术人员。");
            }
        }

        return BaseResultVo.error("网关异常");
    }

    private int getErrorStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        return statusCode != null ? statusCode : HttpStatus.INTERNAL_SERVER_ERROR.value();
    }

    private String getErrorMessage(HttpServletRequest request) {
        final Throwable exc = (Throwable) request.getAttribute("javax.servlet.error.exception");
        return exc != null ? exc.getMessage() : "Unexpected error occurred";
    }
}
